//LEDs des Rahmens
int led_ol_r=0;
int led_ol_g=1;
int led_ol_b=2;

int led_or_r=3;
int led_or_g=4;
int led_or_b=5;

int led_ul_r=6;
int led_ul_g=7;
int led_ul_b=8;

int led_ur_r=9;
int led_ur_g=10;
int led_ur_b=11;

//Pads
int pad_r=12;
int pad_l=13;

char serialReadString[50];//stores the recieved characters
int stringPosition=-1;//stores the current position of my serialReadString

void setup() {
 Serial.begin(115200);
 
 pinMode(led_ol_r,OUTPUT);
 pinMode(led_ol_g,OUTPUT);
 pinMode(led_ol_b,OUTPUT);
  
 pinMode(led_or_r,OUTPUT);
 pinMode(led_or_g,OUTPUT);
 pinMode(led_or_b,OUTPUT);
  
 pinMode(led_ul_r,OUTPUT);
 pinMode(led_ul_g,OUTPUT);
 pinMode(led_ul_b,OUTPUT);
  
 pinMode(led_ur_r,OUTPUT);
 pinMode(led_ur_g,OUTPUT);
 pinMode(led_ur_b,OUTPUT);
  
 pinMode(pad_r,OUTPUT);
 pinMode(pad_l,OUTPUT);

}

void loop()
{
  readSerialLine();
   
   
}

void readSerialLine(){
  while (Serial.available() > 0){ 
      int inByte = Serial.read();
      stringPosition++;
      
      if(inByte=='\n'){
         serialReadString[stringPosition] = 0;
          stringReceived();
          stringPosition=-1;
      }else{
          serialReadString[stringPosition] = inByte; 
      }
  }
}


void stringReceived(){

  //Bei Pad: p<l/r><0/1>      
	if(serialReadString[0]=='p')
	{
		//linkes Pad
		if(serialReadString[1]=='l')
			setPadL(serialReadString[2]);
		//rechtes Pad
		else if(serialReadString[1]=='r')
			setPadR(serialReadString[2]);
	}
	//LED-WERT
	else if(serialReadString[0]=='l')
	{
		int i=3;
		int offset=i;
		char buffer[3];
		
		//Rotwert
		while(i<=6)
		{
			buffer[i-offset]=serialReadString[i];
			i++;
		}
		int r = atoi(buffer);
		offset+=3;
		//Grünwert
		while(i<=9)
		{
			buffer[i-offset]=serialReadString[i];
			i++;
		}
		int g = atoi(buffer);
		offset+=3;
		//Blauwert
		while(i<=12)
		{
			buffer[i-offset]=serialReadString[i];
			i++;
		}
		int b = atoi(buffer);
		
		if(serialReadString[1]=='o' && serialReadString[2]=='l')
			setRGB1(r,g,b);
		else if(serialReadString[1]=='o' && serialReadString[2]=='r')
			setRGB2(r,g,b);
		else if(serialReadString[1]=='u' && serialReadString[2]=='l')
			setRGB3(r,g,b);
		else if(serialReadString[1]=='u' && serialReadString[2]=='r')		
			setRGB4(r,g,b);
		
	}
}	
	

void setRGB1(int r, int g, int b)
{
    analogWrite(led_ol_r, r);
    analogWrite(led_ol_g, g);
    analogWrite(led_ol_b, b);
}

void setRGB2(int r, int g, int b)
{
    analogWrite(led_or_r, r);
    analogWrite(led_or_g, g);
    analogWrite(led_or_b, b);
}

void setRGB3(int r, int g, int b)
{
    analogWrite(led_ul_r, r);
    analogWrite(led_ul_g, g);
    analogWrite(led_ul_b, b);
}

void setRGB4(int r, int g, int b)
{
    analogWrite(led_ur_r, r);
    analogWrite(led_ur_g, g);
    analogWrite(led_ur_b, b);
}

void setPadL(int on)
{
  if(on!='0')
    digitalWrite(pad_l, HIGH);
  else
    digitalWrite(pad_l, LOW);
}

void setPadR(int on)
{
  if(on!='0')
    digitalWrite(pad_r, HIGH);
  else
    digitalWrite(pad_r, LOW);
}
